package com.nowcoder.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nowcoder.entity.Comment;
import com.nowcoder.mapper.CommentMapper;
import com.nowcoder.service.CommentService;
import com.nowcoder.service.DiscussPostService;
import com.nowcoder.utils.NowCoderConstant;
import com.nowcoder.utils.SensitiveFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import java.util.List;

/**
 * @Author liujilong
 * @Project nowcoder
 * @File CommentServiceImpl
 * @Date 2022/1/17 5:31 下午
 **/
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService, NowCoderConstant {

    @Autowired
    private SensitiveFilter sensitiveFilter;

    @Autowired
    private DiscussPostService discussPostService;

    @Override
    public List<Comment> selectCommentByEntity(int entityType, int entityId, int offset, int limit) {
        List<Comment> comments = baseMapper.selectList(new QueryWrapper<Comment>()
                .eq("status", 0)
                .eq("entity_type", entityType)
                .eq("entity_id", entityId)
                .orderByAsc("create_time"));

        int size = comments.size();
        return comments.subList(offset > size ? 0 : offset, Math.min(offset + limit, size));
    }

    @Override
    public int selectCountByEntity(int entityType, int entityId) {
        return baseMapper.selectCount(new QueryWrapper<Comment>()
                .eq("status", 0)
                .eq("entity_type", entityType)
                .eq("entity_id", entityId));
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public int insertComment(Comment comment) {
        if (comment == null) throw new IllegalArgumentException("参数不能为空");

        comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));
        comment.setContent(sensitiveFilter.filter(comment.getContent()));

        int insert = baseMapper.insert(comment);

        if (comment.getEntityType() == ENTITY_TYPE_POST) {
            int count = selectCountByEntity(comment.getEntityType(), comment.getId());
            discussPostService.updateCommentCount(comment.getEntityId(), count++);
        }

        return insert;
    }
}
